//
//  DXDXEmotionView.swift
//  weiBoOfSwift
//
//  Created by simon on 15/12/15.
//  Copyright © 2015年 simon. All rights reserved.
//

import UIKit
let emotionViewReuseIdentifier:String = "DXEmotionViewCell"
class DXEmotionView: UICollectionView {
    
    var emotionViewWillScrollToNewSectionClosure:((newSection:NSIndexPath)->())?
    
//    记录每次传入的DestineSection值
    private var oldImportationSection = 0
//    对外接口设置滚动到指定的位置
    var scrollToDestineSection:Int = 0 {
//        判断每次传入的是否为同一个IndexPath
        didSet{
         if scrollToDestineSection != oldImportationSection {
            let indexPath = NSIndexPath(forItem: 0, inSection: scrollToDestineSection)
            scrollToItemAtIndexPath(indexPath, atScrollPosition: .CenteredHorizontally, animated: false)
     }
            oldImportationSection = scrollToDestineSection
   }
}
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
//        注册cell
        registerClass(DXEmotionViewCell.self, forCellWithReuseIdentifier: emotionViewReuseIdentifier)
        
        setUpUI()
       
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
//    MARK:setUpUI初始化控件
    func setUpUI(){
     backgroundColor = UIColor.clearColor()
     bounces = false
     showsHorizontalScrollIndicator = false
     showsVerticalScrollIndicator = false
     pagingEnabled = true
        
//    设置数据源方法代理
       delegate = self
       dataSource = self
    }
    // MARK: - layoutViews方法,调整子控件的frame
    override func layoutSubviews() {
        super.layoutSubviews()
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.itemSize = self.frame.size
        layout.scrollDirection = .Horizontal
//        添加约束

        
    }
  
//    MARK:懒加载
   
    

}

//
//MARK:DXEmotionView数据源方法

extension DXEmotionView : UICollectionViewDataSource{

    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return DXEmotionViewModel.sharedEmoton.emotions?.count ?? 0
    }
    
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
    
    return DXEmotionViewModel.sharedEmoton.emotions![section].count
        
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
        
   let cell = collectionView.dequeueReusableCellWithReuseIdentifier(emotionViewReuseIdentifier, forIndexPath: indexPath) as! DXEmotionViewCell
        
     let emotions = DXEmotionViewModel.sharedEmoton.emotions![indexPath.section][indexPath.item]
        
    cell.indexPath = indexPath
    cell.emotions = emotions
        return cell
    }
    

}

//MARK:DXEmotionView代理方法,监听每次滑动到新的section
extension DXEmotionView :UICollectionViewDelegate,UIScrollViewDelegate{
    func scrollViewDidScroll(scrollView: UIScrollView) {
     let cells = visibleCells()
        if cells.count > 1 {
            
            let firstCell = cells.first!
            let lastCell = cells.last!
//            根据x 与contenoffse的x偏移量之差来的绝对值比较来计算出,
//            哪个cell所占的屏幕多,越小的cell,在屏幕上占的面积越大
            let cell:UICollectionViewCell
        if abs(Int32(firstCell.x - scrollView.contentOffset.x)) < abs(Int32(lastCell.x - scrollView.contentOffset.x)) {
                
              cell = firstCell
            }else{
             cell = lastCell
            
            }
            
         let targetSection = indexPathForCell(cell)!
            
            self.emotionViewWillScrollToNewSectionClosure?(newSection: targetSection)
        }
  }
    
    private func absOfResult(firstx:CGFloat)->Int32{
    let result =  abs(Int32(x - contentOffset.x))
    
        
    return result
    }
    
}


//MARK:表情view的cell
class DXEmotionViewCell: UICollectionViewCell{

//    数据接口
    var emotions:[DXEmotonModel]?{
        didSet{
           
            for emobtn in emotionButtons {
             emobtn.hidden = true
            }
//            emotonNumLabel.text = "\(emotions!.count)个表情"
            for (i,model) in emotions!.enumerate(){
                let emotionBtn = emotionButtons[i]
                emotionBtn.hidden = false
                emotionBtn.emotionModel = model
            }
        }
    }
    private var emotionButtons:[DXEmtionButton] = [DXEmtionButton]()
//  对外数据设置方法
    var indexPath:NSIndexPath?{
        didSet{
//        tipLabel.text = "第\(indexPath!.section)组,第\(indexPath!.row)页"
        }
    }
//    重写构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
//        初始化控件
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 初始化控件方法
    private func setUpUI(){

//        初始化二十个button
        for _ in 0..<emotonsPageOfNum {
            let emotionBtn = DXEmtionButton()
            emotionBtn.addTarget(self, action: "emtionButtonSelected:", forControlEvents: .TouchUpInside)
//            emotionBtn.backgroundColor = randomCorlor()
            emotionBtn.hidden = true
            emotionBtn.titleLabel?.font = UIFont.systemFontOfSize(29)
            
            emotionButtons.append(emotionBtn)
            contentView.addSubview(emotionBtn)
        }
        
//        添加手势识别
        let longPress =  UILongPressGestureRecognizer(target: self, action: "longPressGresture:")
        
        addGestureRecognizer(longPress)
        
//        添加子控件
        addSubview(deteleButton)
        
    }
    
    
    /**
     将一个表情button的frame迁移到window上,将popview显示在相应的Window中
     */
    private func convertToLastWindow(button:DXEmtionButton){
        //        添加弹出表情视图
        let wind = UIApplication.sharedApplication().windows.last!
        //        将button上对应的frame迁移到另一个坐标系中,
        let windOfBtnframe = button.convertRect(button.bounds, toView: wind)
        
        popView.center.x = CGRectGetMidX(windOfBtnframe)
        popView.y = CGRectGetMinY(windOfBtnframe) - 45
        
        wind.addSubview(popView)
    }
    
    // MARK: -监听点击事件
//    删除按钮点击事件
    @objc private func deteleButtonClick(){
    NSNotificationCenter.defaultCenter().postNotificationName(KEmotionButtonDetele, object: nil)
   
    }
//    表情的手势识别事件
    @objc private func longPressGresture(gresture:UIGestureRecognizer){
        if gresture.state == .Began || gresture.state == .Changed{
         let point = gresture.locationInView(self)
            logPrint("start")
            for btn in emotionButtons{
                if  btn.frame.contains(point) {
                    logPrint("point")
                    popView.emotionBtn.emotionModel = btn.emotionModel
                    convertToLastWindow(btn)
                }
            }
        }
        if gresture.state == .Cancelled || gresture.state == .Ended{
            logPrint("end")
            popView.removeFromSuperview()
        }
    }
    
    @objc private func emtionButtonSelected(sender:DXEmtionButton){
//        logPrint(sender.emotionModel!.chs)
//        将点击的表情保存在最近的表情中
        DXEmotionViewModel.sharedEmoton.saveLatestEmotions(sender.emotionModel!)
    
//        发送通知给控制器点击了哪个button
        NSNotificationCenter.defaultCenter().postNotificationName(emotionButtonDidSelectedNotifity, object: nil, userInfo: ["obj":sender.emotionModel!])
        
        popView.emotionBtn.emotionModel = sender.emotionModel
//      let magnifierVeiw =  DXEmoticonMagnifierView.magnififierView(sender.emotionModel!)
////        添加弹出表情视图
        convertToLastWindow(sender)
//
//        let wind = UIApplication.sharedApplication().windows.last!
////        将button上对应的frame迁移到另一个坐标系中,
//        
//      let windOfBtnframe = sender.convertRect(sender.bounds, toView: wind)
//        
//        magnifierVeiw.center.x = CGRectGetMidX(windOfBtnframe)
//        magnifierVeiw.y = CGRectGetMinY(windOfBtnframe) - 45
//        wind.addSubview(magnifierVeiw)
//       移除视图
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.2 * Double( NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            self.popView.removeFromSuperview()
//            self.popView = nil
          
        }
    
    
    
    }

    override func layoutSubviews() {
        super.layoutSubviews()
//        给20个button设置frame
        for (i,btn) in emotionButtons.enumerate(){
          btn.frame = indexForFrame(i, rowCount: 7, superWith:contentView.width, margin:5)
        }
        deteleButton.frame = indexForFrame(emotionButtons.count, rowCount: 7, superWith:contentView.width, margin:5)
        
    }
    
    /**
     * 根据index返回在九宫格的位置
     */
   private func indexForFrame(index:Int,rowCount:Int,superWith:CGFloat,margin:CGFloat)->CGRect{
        let itemWH = (superWith - margin * 2) / CGFloat(rowCount)
        //       行数
        let row = index / rowCount
        //        列数
        let col = index % rowCount
        
        let x = CGFloat(col) * itemWH + margin
        let y = CGFloat(row) * itemWH - margin
        
        return  CGRect(x: x, y: y, width: itemWH, height: itemWH)
    }
    
//    MARK:懒加载
    lazy var deteleButton:UIButton = {
    
     let deteleButton = UIButton()
        deteleButton.addTarget(self, action: "deteleButtonClick", forControlEvents: .TouchUpInside)
        deteleButton.setImage(UIImage(named: "compose_emotion_delete"), forState: .Normal)
        deteleButton.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: .Highlighted)
     
     return deteleButton
    }()
    
    lazy var popView:DXEmoticonMagnifierView = {
        
       let magnifierVeiw = DXEmoticonMagnifierView.popView()
    
        return magnifierVeiw
    
    
    }()
    
}












